//页面级视图-存储卡读取权限
import React from 'react';
import {View, Alert} from 'react-native';
import {useDebounceEffect, useMount, useSafeState, useUnmount} from 'ahooks';
import {Text, Button} from '@rneui/base';
import {
  check,
  checkMultiple,
  request,
  PERMISSIONS,
  openSettings,
  RESULTS,
} from 'react-native-permissions';

import RNFS from 'react-native-fs';
import RNFetchBlob from 'react-native-blob-util';
import {Dirs, FileSystem} from 'react-native-file-access';

import READ_EXTERNAL_STORAGE from './READ_EXTERNAL_STORAGE';
import WRITE_EXTERNAL_STORAGE from './WRITE_EXTERNAL_STORAGE';
import MOUNT_UNMOUNT_FILESYSTEM from './MOUNT_UNMOUNT_FILESYSTEM';

const checkObjs = {
  READ_EXTERNAL_STORAGE,
  WRITE_EXTERNAL_STORAGE,
  MOUNT_UNMOUNT_FILESYSTEM,
};

export default ({children}) => {
  const [loading, setLoading] = useSafeState(true);
  const [Coms, setComs] = useSafeState([]);
  useMount(() => {
    const newComs = [];
    (async () => {
      for (const [key, Com] of Object.entries(checkObjs)) {
        let v = '';
        try {
          v = await check(PERMISSIONS.ANDROID[key]);
        } catch (e) {
          v = 'denied';
        }
        console.log(key, v);
        const isAllow = v === RESULTS.GRANTED;
        if (!isAllow) {
          newComs.push(Com);
        }
      }
      console.log('newComs', newComs);
      setComs(newComs);
      setLoading(false);
    })();
  });
  if (loading) {
    return <Text></Text>;
  }
  if (Coms.length > 0) {
    return (
      <View
        style={{
          flex: 1,
          alignItems: 'center',
          justifyContent: 'center',
        }}>
        {Coms.map((Item, index) => (
          <Item key={index} />
        ))}
      </View>
    );
  }
  return (
    <>
      {/* {children} */}
      <Button
        title="OpenSettings"
        onPress={() => {
          openSettings();
        }}
        containerStyle={{
          marginTop: 20,
          marginLeft: 10,
          marginRight: 10,
        }}
      />
      <Button
        title="读取文件"
        onPress={() => {
          RNFS.readdir(Dirs.SDCardDir, {})
            .then(result => {
              // result 是文件和目录列表
              console.log('result', result);
            })
            .catch(err => {
              console.log(err.message);
            });
        }}
        containerStyle={{
          marginTop: 30,
          marginLeft: 10,
          marginRight: 10,
        }}
      />
    </>
  );
};

{
  /* <Button
        title="OpenSettings"
        onPress={() => {
          openSettings();
        }}
      /> */
}
